<template>
  <div id="amapDemo" class="amap-demo"></div>
</template>

<script>
import { getWarehousesByDeptIds } from '@/api/api.js'
import { lazyAMapApiLoaderInstance } from 'vue-amap';
export default {
  name: 'MapContainer',
  props:{
    deptId:{ 
      type: [String, Number],
      default: ''
    }
  },
  watch:{
    deptId(newValue, oldValue) {
      if(newValue != oldValue){
        this.$nextTick(()=>{
          this.getWarehousesByDeptIds()
        })
      }
    },
  },
  mounted(){
    //在map实例化之后 再调用接口获取多边形定位
    lazyAMapApiLoaderInstance.load().then(() => {
      this.initMap()
      this.getWarehousesByDeptIds()
    })
  },
  data(){
    const { hideWarehouse } = this.$route.query
    return{
      map: null, // 地图
      hideWarehouse: !!hideWarehouse,
    }
  },
  methods:{
    initMap(center) {
      this.map = new AMap.Map("amapDemo", {
        resizeEnable: true,
        center: center, //地图中心点
        zoom: 12, //地图显示的缩放级别
      });
      this.map.on('mousedown', () => {
        this.$emit('mousedown')
      })
    },
    getWarehousesByDeptIds(s){
      
      let data = {
        deptId: this.deptId ? this.deptId : 1
      }
      getWarehousesByDeptIds(data).then(res=>{
          let result = res.data;
          let lao = {
            longitude: res.data[0].longitude,
            latitude: res.data[0].latitude
          }
          this.map.clearMap()
          this.map.setCenter([lao.longitude, lao.latitude])
          result.map((item,resultindex) => {
            if(result[resultindex].geoJson.geometry !== '') {
              let polygon = new AMap.Polygon({
                strokeWeight: 2,
                path: result[resultindex].geoJson.geometry.coordinates[0],
                fillOpacity: 0.4,
                fillColor: "#80d8ff",
                strokeColor: "#0091ea",
                events: {
                  click: () => {
                  }
                }
              });
              this.map.add(polygon)

              if (!this.hideWarehouse) {
                let marker = new AMap.Marker({
                  position: new AMap.LngLat(item.longitude, item.latitude),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                  label: {
                    content: item.name,
                    direction: 'top'
                  },
                });
                this.map.add(marker)
              }
            }
          })
      })
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.amap-demo{
  padding:0PX;
  margin: 0PX;
  width: 100%;
  height: calc(100vh - 188PX);
}
</style>
